﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Threading;


namespace Chat_WebServer.Controllers
{
    public class YahooMessageController : ApiController
    {
        private const string URL_YM_MESSAGE = "http://developer.messenger.yahooapis.com/v1/message/yahoo/{{USER}}";
        private const string URL_YM_NOTIFICATION = "http://developer.messenger.yahooapis.com/v1/notifications";
        private const string CONSUMER_KEY = "dj0yJmk9a3hXZFk2VjhxbDE1JmQ9WVdrOVVtbDFhako2TnpRbWNHbzlNVE0yTURjME5qazJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0yMg--";
        private const string CONSUMER_SECRET = "a21a9f4625f6b4fcc5eca8901ac343352b8d4406";
        private OAuthBase oauth = new OAuthBase();

        public string POST(string user, string mess, string oauth_token, string oauth_token_secret, string sessionID)
        {
            oauth_token = oauth_token.Replace("=", "%3D");
            var requestURL = URL_YM_MESSAGE + "?oauth_consumer_key=" + CONSUMER_KEY
                            + "&oauth_nonce=" + oauth.GenerateNonce()
                            + "&oauth_signature=" + CONSUMER_SECRET + "%26" + oauth_token_secret
                            + "&oauth_signature_method=PLAINTEXT"
                            + "&oauth_timestamp=" + oauth.GenerateTimeStamp()
                            + "&oauth_token=" + oauth_token
                            + "&oauth_version=1.0"
                            + "&sid=" + sessionID;
            requestURL = requestURL.Replace("{{USER}}", user);
            HttpWebRequest request = HttpWebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json; charset=utf-8";
            string content = "{\"message\":\"" + mess + "\"}";
            byte[] requestBytes = new UTF8Encoding().GetBytes(content);
            request.ContentLength = requestBytes.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(requestBytes, 0, requestBytes.Length);
            }
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return mess;
                    }
                }
            }
            catch
            {
                Console.WriteLine("Unauthor");
            }
            return String.Empty;
        }

        public List<string> GET(string oauth_token, string oauth_token_secret, string sessionID, string seq)
        {
            List<string> mess = new List<string>();
            oauth_token = oauth_token.Replace("=", "%3D");
            string requestURL = URL_YM_NOTIFICATION + "?oauth_consumer_key=" + CONSUMER_KEY
                                + "&oauth_nonce=" + oauth.GenerateNonce()
                                + "&oauth_signature=" + CONSUMER_SECRET + "%26" + oauth_token_secret
                                + "&oauth_signature_method=PLAINTEXT"
                                + "&oauth_timestamp=" + oauth.GenerateTimeStamp()
                                + "&oauth_token=" + oauth_token
                                + "&oauth_version=1.0"
                                + "&sid=" + sessionID
                                + "&seq=" + seq
                                + "&count=100";
            int count = 0;
            while (count <= 11)
            {
                HttpWebRequest request = HttpWebRequest.Create(requestURL) as HttpWebRequest;
                request.Method = "GET";
                request.ContentType = "application/json; charset=utf-8";
                try
                {
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            StreamReader reader = new StreamReader(response.GetResponseStream());
                            String str = reader.ReadToEnd();
                            JObject obj = JObject.Parse(str);
                            JArray arr = JArray.Parse(obj["responses"].ToString());
                            int sequence = 0;
                            foreach (var o in arr)
                            {
                                if (o["message"] != null)
                                {
                                    string sender = (string)o["message"]["sender"];
                                    string msg = (string)o["message"]["msg"];
                                    mess.Add(sender + "@" + msg);
                                    if ((int)o["message"]["sequence"] > sequence)
                                        sequence = (int)o["message"]["sequence"];
                                }
                            }
                            if (mess.Count <= 0)
                                Thread.Sleep(3000);
                            else
                            {
                                mess.Add((sequence + 1).ToString());
                                return mess;
                            }
                            count++;
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("exception");
                    return null;
                }
            }
            return null;
        }
    }
}
